/*
 * @Author: Wangjun
 * @Date: 2022-10-14 16:27:24
 * @LastEditTime: 2025-01-02 14:22:47
 * @LastEditors: wangjun haodreams@163.com
 * @Description:
 * @FilePath: \libs\apps\app.go
 * hnxr
 */
package apps

import (
	"fmt"
	"log"
	"os"
	"os/exec"
	"path/filepath"
	"runtime"
	"strings"
	"time"

	"gitee.com/haodreams/libs/easy"
)

// Show 显示窗口，Windows 下有效
func ShowConsole() (err error) {
	ShowConsoleWindow(true)
	return
}

// Hide 关闭窗口，Windows 下有效
func HideConsole() (err error) {
	ShowConsoleWindow(false)
	return
}

// Restart 重启进程
func Restart() (err error) {
	var cmd *exec.Cmd
	if len(os.Args) == 1 {
		cmd = exec.Command(os.Args[0])
	} else {
		cmd = exec.Command(os.Args[0], os.Args[1:]...)
	}
	err = cmd.Start()
	if err == nil {
		os.Exit(1)
	}
	return err
}

// DelayRestart 延时重启
func DelayRestart(sec int64) {
	go func() {
		time.Sleep(time.Second * time.Duration(sec))
		err := Restart()
		log.Println("Restart:", err)
	}()
}

// MakeRegisterAutoStart 注册开机自启动
func MakeRegisterAutoStart(autoInstall bool) {
	if runtime.GOOS == "windows" {
		binaryPath, _ := filepath.Abs(os.Args[0])
		bin := filepath.Base(binaryPath)
		bin = strings.TrimSuffix(bin, filepath.Ext(bin))
		if autoInstall {
			cmd := exec.Command("reg", "add", "HKLM\\Software\\Microsoft\\Windows\\CurrentVersion\\Run", "/v", bin, "/d", binaryPath, "/f")
			cmd.Run()
			return
		}
		buf := easy.NewBufferWithSize(4096)
		buf.WriteString("Windows Registry Editor Version 5.00\r\n\r\n")
		buf.WriteString("[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run]\r\n")
		binaryPath = strings.ReplaceAll(binaryPath, "\\", "\\\\")
		buf.WriteString(`"` + bin + `"="\"` + binaryPath + "\\\"\"\r\n")
		os.WriteFile(fmt.Sprintf("auto_start_%s.reg", bin), buf.Bytes(), 0644)

		// cmd := exec.Command("reg", "delete", "HKLM\\Software\\Microsoft\\Windows\\CurrentVersion\\Run", "/v", bin, "/f")
		// cmd.Run()
		return
	}
}
